package com.java.socket.udp.singleclient.client;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.nio.charset.Charset;

/**
 * UDP协议下的单个客户端网络通信.
 * <p>客户端实例</p>
 *
 * @author xzmeasy
 * @version 1.0
 * @since 星期一 十二月,2018
 */
@SuppressWarnings("Duplicates")
public class DatagramClientExample {

    public static void main(String[] args) {
        try {
            // 创建发送方DatagramSocket
            DatagramSocket socket = new DatagramSocket();
            // 创建发送方数据包
            byte[] bytes = "发送方发送的数据".getBytes();
            DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
            packet.setAddress(InetAddress.getByName("localhost"));
            packet.setPort(8888);
            // 发送数据包
            socket.send(packet);
            // 关闭DatagramSocket
            socket.close();


            // 接收接收方的反馈数据，端口号不能与上边一样，因为端口号已经被占用
            DatagramSocket receiveSocket = new DatagramSocket(8889);
            byte[] bytes1 = new byte[1024];
            DatagramPacket receive = new DatagramPacket(bytes, bytes.length);
            receiveSocket.receive(receive);
            System.out.println("接收方反馈的数据:" + new String(bytes, Charset.forName("utf-8")));
            // 关闭socket
            receiveSocket.close();
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
